<?php
// 应用公共文件

use app\common\service\file\FileService;

function ajax_return($code = 0, $msg = '', $data = [])
{
    $res      = ['code' => $code, 'msg' => $msg, 'data' => $data];
    $response = \think\Response::create($res, 'json');
    throw new \think\exception\HttpResponseException($response);
}

function url(string $url = '', array $vars = [], $suffix = true, $domain = true)
{
    return \think\facade\Route::buildUrl($url, $vars)->suffix($suffix)->domain($domain);
}

function rand_str($len = 6)
{
    $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $res = '';
    for ($i = 0; $i < $len; $i++) {
        $key = rand(0, strlen($str) - 1);
        $res .= $str[$key];
    }
    return $res;
}

function array_get($array, $key, $default = null)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

/**
 * 公共数据导出实现功能
 * @param string $expTitle
 * @param array $expCellName [['a','A']]
 * @param array $expTableData [['a'=>1]]
 * @param array $textValue ['a']
 */
function export_exl($expTitle, $expCellName, $expTableData, $textValue = [])
{
    $fileName    = $expTitle . date('_YmdHis'); //or $xlsTitle 文件名称可根据自己情况设定
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet       = $spreadsheet->getActiveSheet();
    $sheet->setTitle($fileName);

    $cellNum  = count($expCellName);
    $dataNum  = count($expTableData);
    $cellName = [];
    $cellRow  = 'A';
    for ($i = 0; $i < $cellNum; $i++) {
        $cellName[] = $cellRow;
        $cellRow++;
    }

    for ($i = 0; $i < $cellNum; $i++) {
        $sheet->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
    }

    // Miscellaneous glyphs, UTF-8
    for ($i = 0; $i < $dataNum; $i++) {
        for ($j = 0; $j < $cellNum; $j++) {
            if (in_array($expCellName[$j][0], $textValue)) {
                $sheet->setCellValueExplicit($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            } else {
                $sheet->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
    }

    ob_end_clean();
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel');
    header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}


/**
 * @param string $file
 * @param array $cell
 * @param int $crop
 * @return array
 */
function import_exl($file = '', $cell = [], $crop = 0)
{
    //$file = iconv("utf-8", "gb2312", $file);   //转码
    // 1. 检测文件是否存在
    if (empty($file) or !file_exists($file)) {
        ajax_return(1, '文件不存在!');
    }

    // 2. 根据文件类型创建阅读器
    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);

    // 3. 获取第一个工作表
    $worksheet = $spreadsheet->getActiveSheet();

    // 4. 获取行列范围
    $highestRow         = $worksheet->getHighestRow();
    $highestColumn      = $worksheet->getHighestColumn();
    $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

    // 5. 循环读取数据
    $data = [];
    for ($row = 1; $row <= $highestRow; $row++) {
        if ($row > $crop) {
            for ($col = 1; $col <= $highestColumnIndex; $col++) {
                $cellValue = $worksheet->getCell([$col, $row])->getValue();
                // 处理特殊类型（公式/日期）
                if ($cellValue instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) {
                    $cellValue = $cellValue->getPlainText();
                } else {
                    $cellValue = (string)$cellValue;
                }
                $data[$row][$cell[$col - 1]] = $cellValue;
            }
        }
    }

    return array_values($data);
}